package com.huang.community.controller;

import com.huang.community.common.CommunityConstant;
import com.huang.community.model.NewPage;
import com.huang.community.pojo.DiscussPost;
import com.huang.community.Entity.SearchResult;
import com.huang.community.service.ElasticsearchService;
import com.huang.community.service.LikeService;
import com.huang.community.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Es搜索控制器
 * @author TianTian
 * @date 2022/4/28 21:32
 */
@Controller
public class ElasticSearchController implements CommunityConstant {
    private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchController.class);
    @Autowired
    ElasticsearchService elasticSearchService;
    @Autowired
    UserService userService;
    @Autowired
    LikeService likeService;
    //搜索
    @GetMapping("search")
    public String search(String keyword, NewPage page, Model model) {
        try {
            SearchResult searchResult = elasticSearchService.searcherDiscussPost(keyword, (page.getCurrent() - 1)*10, page.getLimit());
            List<Map<String,Object>> discussPosts = new ArrayList<>();
            List<DiscussPost> list = searchResult.getList();
            if(list != null) {
                for (DiscussPost post : list) {
                    Map<String,Object> map = new HashMap<>();
                    //帖子 和 作者
                    map.put("post",post);
                    map.put("user",userService.findUserById(Integer.valueOf(post.getUserId())));
                    // 点赞数目
                    map.put("likeCount",likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                    discussPosts.add(map);
                }
            }
            model.addAttribute("discussPosts",discussPosts);
            model.addAttribute("keyword",keyword);
            //分页信息
            page.setPath("/search?keyword=" + keyword);
            page.setRows(searchResult.getTotal() == 0 ? 0 : (int) searchResult.getTotal());
        } catch (IOException e) {
            LOGGER.error("系统出错，没有数据：" + e.getMessage());
        }
        return "/site/search";
    }

}
